<template>
  <div class="login-form">
    <Form ref="formLogin" :model="formLogin" :rules="ruleLogin" inline>
      <FormItem prop="userToken">
        <i-input
          type="text"
          v-model="formLogin.userToken"
          placeholder="User Token"
        >
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
        </i-input>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="handleLoginSubmit()">Login</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from '@/plugins/class-component-hooks'

import { playerModule } from '@/store'

import { isThis } from '@/types/Errors'
import { GraphQLError } from 'graphql'

@Component
export default class Login extends Vue {
  private formLogin = {
    userToken: ''
  }

  private ruleLogin = {
    userToken: [
      {
        required: true
      }
    ]
  }

  async loginSubmit() {
    let data = await playerModule.login({
      loginToken: this.formLogin.userToken,
      graphqlClient: this.$apollo.getClient()
    })

    // jump to room-list
    this.$router.push({
      name: 'room-list'
    })
  }

  handleLoginSubmit() {
    // @ts-ignore
    this.$refs['formLogin'].validate(valid => {
      if (valid) {
        this.loginSubmit()
          .then(() => this.$Message.success('提交成功!'))
          .catch((err: GraphQLError) => {
            isThis(err)
              .ErrNoToken(() => {
                this.$Message.error('密码错误, 请检查密码')
              })
              .ErrInvalidToken(() => {
                this.$Message.error('密码错误, 请检查密码')
              })
              .handle()
          })
      } else {
        this.$Message.error('提交失败!')
      }
    })
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss"></style>
